package com.chatplus.application.service.wxmp.handler;

import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.entity.account.UserEntity;
import com.chatplus.application.domain.entity.account.WechatUserEntity;
import com.chatplus.application.enumeration.WechatUserStatusEnum;
import com.chatplus.application.service.account.UserService;
import com.chatplus.application.service.account.WechatUserService;
import com.chatplus.application.service.wxmp.impl.WeChatMpService;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 扫码事件处理器
 *
 * @author chj
 */
@Service
public class ScanHandler extends AbstractHandler {
    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ScanHandler.class);
    private final WechatUserService wechatService;
    private final UserService userService;

    public ScanHandler(WeChatMpService weChatMpService,
                       @Lazy WechatUserService wechatService,
                       UserService userService) {
        super(weChatMpService);
        this.wechatService = wechatService;
        this.userService = userService;
    }

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
        LOGGER.message("接收到扫码事件").context("OPENID", wxMessage.getFromUser()).info();
        WechatUserEntity weChatUser = this.wechatService.getOneByOpenidAndAppId(wxMessage.getFromUser(), wxMessage.getToUser());
        if (weChatUser == null) {
            weChatUser = new WechatUserEntity();
            weChatUser.setOpenId(wxMessage.getFromUser());
            weChatUser.setAppId(wxMessage.getToUser());
            UserEntity userEntity = userService.wxOneClickRegister();
            weChatUser.setUserId(userEntity.getId());
        }
        weChatUser.setStatus(WechatUserStatusEnum.FOLLOWED);
        this.wechatService.saveOrUpdate(weChatUser);
        return this.handleKey(weChatUser, wxMessage);
    }

    /**
     * 事理key事件
     */
    private WxMpXmlOutMessage handleKey(WechatUserEntity weChatUser, WxMpXmlMessage wxMpXmlMessage) {
        return this.handleByEventKey(wxMpXmlMessage.getEventKey(), weChatUser, wxMpXmlMessage);
    }
}
